package com.itheima.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.dto.OrderInfoDto;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.PayUtils;
import com.itheima.vo.OrderInfoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：yuanjian
 * @date ：Created in 2020/11/17 16:36
 * @description：
 */
@RestController
@RequestMapping("/order")
public class OrderMobileController {

    @Reference(mock ="com.itheima.mock.MockService" )
//    @Reference
    private OrderService orderService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    //发送验证码
    @GetMapping("sendSmsCode/{telephone}")
    public Result sendSmsCode(@PathVariable("telephone") String telephone){
        rabbitTemplate.convertAndSend("sms_exchange","sms_routing_key",telephone);
        return new Result(true,"发送成功");
    }

    //提交订单
    @PostMapping("/add")
    public Result addOrder(@RequestBody OrderInfoDto orderInfoDto) {
        String orderId = orderService.addOrder(orderInfoDto).toString();
        if (Integer.parseInt(orderId)==0){

            return new Result(false,"当前页面火爆，请稍后刷新重试");
        }

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor(){

            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("30000");
                return message;
            }
        };
        rabbitTemplate.convertAndSend("addOrder_exchange","addOrder_routing_key",orderId,messagePostProcessor);
        return new Result(true,"预约成功",orderId);
    }

    //订单查询成功 页面所需要的信息
    @GetMapping("findOrderInfo/{id}")
    public Result findOrderInfo(@PathVariable("id") String orderId){
        OrderInfoVo orderInfo = orderService.findOrderInfo(Long.parseLong(orderId));
        return new Result(true,"预约成功",orderInfo);
    }


    //创建微信支付订单
    @GetMapping("createPayOrder/{orderNo}")
    public Result createPayOrder(@PathVariable("orderNo") String orderNo) throws Exception {
        //设置每次支付一分钱
        Integer totalPay = 1;
        String payUrl = PayUtils.createOrder(orderNo, totalPay);
        return new Result(true,"创建成功",payUrl);

    }

    //微信支付成功后的回调函数
    @PostMapping("payNotify")
    public void PayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 1.接收请求参数（xml）
        ServletInputStream in = request.getInputStream();
        // 2.将xml转为java对象
        XmlMapper xmlMapper = new XmlMapper();
        //保存着微信支付成功返回的信息
        Map param = xmlMapper.readValue(in, Map.class);
        // 3.调用orderService，修改订单状态
        orderService.updateStatus((String) param.get("out_trade_no"));
        // 4.返回微信平台，接收成功..
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        // 将map转为xml
        String xml = xmlMapper.writeValueAsString(result);
        response.setContentType("application/xml;charset=utf-8");
        response.getWriter().write(xml);


    }

    @GetMapping("/isPay/{orderNo}")
    public Result isPay(@PathVariable("orderNo") String orderNo){

        String isPay = orderService.isPay(orderNo);
        return new Result(true,"",isPay);
    }


}
